package com.penghaisoft.microwms.materialhand.web.outwarehouse.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.data.model.RawRequisition;
import com.penghaisoft.microwms.common.data.model.RawRequisitionSn;
import com.penghaisoft.microwms.common.dto.HandResp;
import com.penghaisoft.microwms.common.dto.RawOrderOutDto;
import com.penghaisoft.microwms.common.dto.RawOrderOutSnDto;
import com.penghaisoft.microwms.common.dto.RawRequisitionMesDto;
import com.penghaisoft.microwms.common.service.IMesInterfaceService;
import com.penghaisoft.microwms.common.service.MesProperties;
import com.penghaisoft.microwms.common.wms.model.RawStorageSn;
import com.penghaisoft.microwms.materialhand.web.insidewarehouse.service.IMaterialHandInsideWhService;
import com.penghaisoft.microwms.materialhand.web.outwarehouse.service.IMaterialRequisitionService;
import com.penghaisoft.microwms.materialhand.web.outwarehouse.service.RawOrderOutService;
import com.penghaisoft.microwms.materialhand.web.outwarehouse.service.RawOrderOutSnService;

import lombok.extern.slf4j.Slf4j;

/**
 * 原材料领料出库手持服务 Created by 王治国 on 2018/5/31.
 */
@RestController
@RequestMapping(value = "raw/rawoutwhhand")
@Slf4j
public class RawOrderOutController {

	@Autowired
	private RawOrderOutService rawOrderOutService;

	@Autowired
	private RawOrderOutSnService rawOrderOutSnService;

	@Autowired
	private IMaterialHandInsideWhService iMaterialHandInsideWhService;

	@Autowired
	private IMaterialRequisitionService iMaterialRequisitionService;

	@Autowired
	private IMesInterfaceService mesInterfaceService;

	@Resource
	private MesProperties mesProperties;

	/**
	 * 第一步：提单 提取领料单号、合同单号需求型号、型号类型、需求数量、已扫数量、单位
	 *
	 * @return
	 */
	@PostMapping("queryOrder")
	public HandResp queryOrderByCode(@RequestBody RawOrderOutDto rawOrderOutDto) {
		HandResp resp = new HandResp();
//        0：普通--匹配（PE管匹配钢管）1：返修（PE管匹配自身长度） 2；普通--独发（无须PE管匹配钢管）3：辅料 4：补料',
		List<RawOrderOutDto> list = rawOrderOutService.findOrderInfo(rawOrderOutDto);
		int sucFlag = 1;// 领料单是否已经完成扫码 0：未完成 1：完成
		if (list.size() > 0) {
			for (RawOrderOutDto order : list) {
//            	0 新建 1 发货中 2发货完成 3扫码完成
				if ("0".equals(order.getRequisitionStatus()) || "1".equals(order.getRequisitionStatus())
						|| "3".equals(order.getRequisitionStatus())) {
					sucFlag = 0;
					break;
				}
			}

			if (sucFlag == 1) {
				resp.setCode(Constant.FAIL);
				resp.setMsg("该领料单已经发货完成！");
				return resp;
			}
		} else {
			resp.setCode(Constant.FAIL);
			resp.setMsg("该领料单不存在！");
			return resp;
		}

		if (!Constant.FAIL.equals(resp.getCode())) {
			resp.setCode(Constant.SUCCESS);
		}
		return resp;
	}

	/**
	 * 第二步：扫条码
	 *
	 * @param rawOrderOutSnDto（条码、领料单号）
	 * @return
	 * @wzhg 1866
	 */
	@PostMapping("scan")
	public HandResp scanBarcode(@RequestBody RawOrderOutSnDto rawOrderOutSnDto) {
		HandResp result = new HandResp();

		int sucFlag = 1;// 领料单是否已经完成扫码 0：未完成 1：完成
		RawOrderOutDto orderOutDto = new RawOrderOutDto();
		orderOutDto.setRequisitionNo(rawOrderOutSnDto.getRequisitionNo());// 领料单号
//        领料单类型：0：普通（PE管匹配钢管）1：返修（PE管匹配自身长度）
//        orderOutDto.setRequisitionType("0");
		List<RawOrderOutDto> orderOutDtos = rawOrderOutService.findOrderInfo(orderOutDto);
//        // 0.判断该领料单号是否存在 以及 是否已经扫码完成
//        if (orderOutDtos.size() > 2){
//            result.setCode(Constant.FAIL);
//            result.setMsg("领料单数据异常！");
//            return result;
//        }else 
//        if (orderOutDtos.size() > 0){
//            for (RawOrderOutDto order : orderOutDtos) {
//                if ("0".equals(order.getRequisitionStatus()) || "1".equals(order.getRequisitionStatus())) {
//                    sucFlag = 0;
//                    break;
//                }
//            }
//            if (sucFlag == 1) {
//                result.setCode(Constant.FAIL);
//                result.setMsg("该领料单已经扫码完成！");
//                return result;
//            }
//        } else {
//            result.setCode(Constant.FAIL);
//            result.setMsg("该领料单不存在！");
//            return result;
//        }
		if (orderOutDtos.size() <= 0) {
			result.setCode(Constant.FAIL);
			result.setMsg("领料单号不存在！");
			return result;
		}

		// 1.判断条码是否存在，是否已扫描，是否归属合同号 库存明细表/出库明细表/ 比较两个表的合同单号和领料单号（不需要，与第二步重复）
		RawStorageSn rawStorageSn = new RawStorageSn();
		rawStorageSn.setBarcode(rawOrderOutSnDto.getBarcode());
		rawStorageSn.setActiveFlag("1");
		rawStorageSn.setBarcodeStatus("0");
		List<RawStorageSn> rawStorageSns = new ArrayList<RawStorageSn>();
		rawStorageSns = iMaterialHandInsideWhService.findRawStorageSnAbs(rawStorageSn);
		if (rawStorageSns.size() == 0) {
			result.setCode(Constant.FAIL);
			result.setMsg("该条码不在库存中，请核查！");
			return result;
		} else if (rawStorageSns.size() > 1) {
			result.setCode(Constant.FAIL);
			result.setMsg("库存中该条码重复！");
			return result;
		} else {
			RawStorageSn storageSn = rawStorageSns.get(0); // 库存条码

			if ("2".equals(storageSn.getBarcodeStatus())) {
				result.setCode(Constant.FAIL);
				result.setMsg("该条码已出库！");
				return result;
			} else if ("1".equals(storageSn.getBarcodeStatus())) {
				result.setCode(Constant.FAIL);
				result.setMsg("该条码已被冻结！");
				return result;
			}

			orderOutDto = orderOutDtos.get(0);
			// 判断条码是否归属领料单号对应的合同号
			if (!storageSn.getContractNo().equals(orderOutDto.getContractNo())) {
				result.setCode(Constant.FAIL);
				result.setMsg("条码所属的合同号与该领料单号对应的合同号不一致！");
				return result;
			}

			// 对应生产钢管成品的PE管才需要配套，管件的PE不需要走配套逻辑
			Boolean peFlag = false;
			for(String str : Constant.PE_LIST) {
				if(str.equals(storageSn.getModelType())) {
					peFlag = true;
					break;
				}
			}
			if (peFlag && "0".equals(orderOutDto.getRequisitionType())) {
//                //PE管扫描
//                result = rawOrderOutSnService.scanPE1(rawOrderOutSnDto, storageSn);
				try {
					result = rawOrderOutSnService.scanPENew(rawOrderOutSnDto, storageSn);
				} catch (RuntimeException e) {
					result.setCode(Constant.FAIL);
					result.setMsg(e.getMessage());
				}
			} else {
//            	0：普通--匹配（PE管匹配钢管）1：返修（PE管匹配自身长度） 2；普通--独发（无须PE管匹配钢管）3：辅料 4：补料',
				// 非PE管匹配钢管的情况
				result = rawOrderOutSnService.scanElse(rawOrderOutSnDto, storageSn);
			}
			result.setList(rawStorageSns);
		}

		// 7.扫码结束
		return result;
	}

	/**
	 * @Title delBarcode
	 * @Description 退扫条码
	 * @author luoteng
	 * @date 2018年7月3日:上午10:06:43
	 * @param rawOrderOutSnDto
	 * @return HandResp
	 */
	@PostMapping("del")
	public HandResp delBarcode(@RequestBody RawOrderOutSnDto rawOrderOutSnDto) {
		HandResp resp = new HandResp();

		resp = rawOrderOutSnService.delBarCode(rawOrderOutSnDto);

		return resp;
	}

	/**
	 * @Title: partsConfirm
	 * @Description: 分批上传
	 * @date 2019年3月27日 下午5:21:46
	 * @author luoteng
	 * @param rawOrderOutDto
	 * @return HandResp
	 */
	@PostMapping("parts/confirm")
	public HandResp partsConfirm(@RequestBody RawOrderOutDto rawOrderOutDto) {
		HandResp resp = new HandResp();

		// 0：普通--匹配（PE管匹配钢管）1：返修（PE管匹配自身长度） 2；普通--独发（无须PE管匹配钢管）3：辅料 4：补料',
		rawOrderOutDto.setRequisitionType("0");
		List<RawOrderOutDto> orderOutDtos = rawOrderOutService.findOrderInfoNew(rawOrderOutDto);

		if (orderOutDtos != null && !orderOutDtos.isEmpty()) {
			// 如果是PE管匹配钢管的订单
			if ("0".equals(orderOutDtos.get(0).getRequisitionType())) {
				RawRequisitionSn yz = new RawRequisitionSn();
				yz.setRequisitionNo(rawOrderOutDto.getRequisitionNo());
				yz.setRequisitionType("0");
				
//				yz.setModelTypeNotEqual(Constant.MODEL_PE);
				yz.setModelTypeNotEqualList(Constant.PE_LIST);
				
//	            0未传mes;1已传mes
				yz.setMesStatus("0");
				yz.setActiveFlag("1");
				yz.setUserDefined3IsNull("peBarCode");
				List<RawRequisitionSn> yzList = rawOrderOutSnService.queryByAnySnList(yz);
				if (yzList != null && !yzList.isEmpty()) {
					resp.setCode(Constant.FAIL);
					resp.setMsg("该领料单存在钢管未匹配PE管！");
					return resp;
				}

				RawRequisitionSn yz1 = new RawRequisitionSn();
				yz1.setRequisitionNo(rawOrderOutDto.getRequisitionNo());
				
//				yz1.setModelType(Constant.MODEL_PE);
				yz1.setModelTypeList(Constant.PE_LIST);
				
				List<RawRequisitionSn> yzList1 = rawOrderOutSnService.queryDuoSaoPeList(yz1);
				if (yzList1 != null && !yzList1.isEmpty()) {
					resp.setCode(Constant.FAIL);
					resp.setMsg("该领料单存在待退扫的PE管！");
					return resp;
				}
			}
		}

		String url = mesProperties.getUrl() + "/imes-provider/productplan/follow/ordersplit/materialin";

		RawRequisitionSn rawRequisitionSn = new RawRequisitionSn();
		rawRequisitionSn.setRequisitionNo(rawOrderOutDto.getRequisitionNo());
//        0未传mes;1已传mes
		rawRequisitionSn.setMesStatus("0");
		rawRequisitionSn.setActiveFlag("1");
		List<RawRequisitionSn> list = iMaterialRequisitionService.queryMesNormalList(rawRequisitionSn);

		if (list == null || list.isEmpty()) {
			resp.setCode(Constant.FAIL);
			resp.setMsg("该领料单没有待上传记录！");
			return resp;
		}

		List<RawRequisitionMesDto> mesList = new ArrayList<RawRequisitionMesDto>();
		for (RawRequisitionSn tmp : list) {
			RawRequisitionMesDto mesOb = new RawRequisitionMesDto();
			mesOb.setMaterialId(tmp.getBarcode());
			mesOb.setMaterialCode(tmp.getModel());
			mesOb.setMaterialType(tmp.getModelType());
			mesOb.setQuantity(tmp.getAmount());
			mesOb.setMeasureUnit(tmp.getUnit());
			mesList.add(mesOb);
		}

		JSONObject ob = new JSONObject();
		ob.put("receiptNo", rawOrderOutDto.getRequisitionNo());
		ob.put("salesCode", list.get(0).getContractNo());
//        领料类型 1 普通料（钢管、pe管、管件） 2 辅料
		ob.put("type", "1");
		ob.put("materialList", mesList);
//		调mes新增接口
		HandResp handResp = mesInterfaceService.publicWSResp(url, MediaType.APPLICATION_JSON_TYPE, ob.toJSONString());
		if (handResp.getCode() != null && handResp.getCode().equals("0")) {
			resp.setCode(handResp.getCode());
			resp.setMsg(handResp.getMsg());
			return resp;
		} else {
//			更新领料明细表
			iMaterialRequisitionService.updateMesStatus(list, rawOrderOutDto.getLoginName());
		}

		resp.setCode(Constant.SUCCESS);
		resp.setMsg("确认成功！");
		return resp;
	}
	
	/**
	 * @Title: confirm
	 * @Description: 最终确认
	 * @date 2019年3月27日 下午7:50:22
	 * @author luoteng
	 * @param rawOrderOutDto
	 * @return HandResp   
	 */
	@PostMapping("confirm")
	public HandResp confirm(@RequestBody RawOrderOutDto rawOrderOutDto) {
		HandResp resp = new HandResp();

//      0：普通--匹配（PE管匹配钢管）1：返修（PE管匹配自身长度） 2；普通--独发（无须PE管匹配钢管）3：辅料 4：补料',
		rawOrderOutDto.setRequisitionType("0");
		List<RawOrderOutDto> orderOutDtos = rawOrderOutService.findOrderInfoNew(rawOrderOutDto);

		// 如果是PE管匹配钢管的订单
		if (orderOutDtos != null && !orderOutDtos.isEmpty()) {
			if (orderOutDtos.size() == 2) {
				for (RawOrderOutDto orderOutDto : orderOutDtos) {
					if (Constant.MODEL_L.equals(orderOutDto.getModelType())
							|| Constant.MODEL_W.equals(orderOutDto.getModelType())
							|| Constant.MODEL_Z.equals(orderOutDto.getModelType())
							|| Constant.MODEL_LDXG.equals(orderOutDto.getModelType())) {
						BigDecimal realAmount = orderOutDto.getRealAmount() == null ? BigDecimal.ZERO
								: orderOutDto.getRealAmount();
						BigDecimal requireAmount = orderOutDto.getRequireAmount() == null ? BigDecimal.ZERO
								: orderOutDto.getRequireAmount();
						if (realAmount.compareTo(requireAmount) == -1) {
							resp.setCode(Constant.FAIL);
							resp.setMsg("该领料单号下还有未扫码完成的任务！");
							return resp;
						}
					}
				}
			} else {
				resp.setCode(Constant.FAIL);
				resp.setMsg("领料单数量有错误，请联系运维人员核查！");
				return resp;
			}
			
			RawRequisitionSn yz = new RawRequisitionSn();
			yz.setRequisitionNo(rawOrderOutDto.getRequisitionNo());
			yz.setRequisitionType("0");
			
//			yz.setModelTypeNotEqual(Constant.MODEL_PE);
			yz.setModelTypeNotEqualList(Constant.PE_LIST);
			
//          0未传mes;1已传mes
			yz.setMesStatus("0");
			yz.setActiveFlag("1");
			yz.setUserDefined3IsNull("peBarCode");
			List<RawRequisitionSn> yzList = rawOrderOutSnService.queryByAnySnList(yz);
			if (yzList != null && !yzList.isEmpty()) {
				resp.setCode(Constant.FAIL);
				resp.setMsg("该领料单存在钢管未匹配PE管！");
				return resp;
			}

			RawRequisitionSn yz1 = new RawRequisitionSn();
			yz1.setRequisitionNo(rawOrderOutDto.getRequisitionNo());
			
//			yz1.setModelType(Constant.MODEL_PE);
			yz1.setModelTypeList(Constant.PE_LIST);
			
			List<RawRequisitionSn> yzList1 = rawOrderOutSnService.queryDuoSaoPeList(yz1);
			if (yzList1 != null && !yzList1.isEmpty()) {
				resp.setCode(Constant.FAIL);
				resp.setMsg("该领料单存在待退扫的PE管！");
				return resp;
			}
		}
		
		RawOrderOutDto rawOrderOutDtoNew = new RawOrderOutDto();
		rawOrderOutDtoNew.setRequisitionNo(rawOrderOutDto.getRequisitionNo());
		List<RawOrderOutDto> orderOutDtos1 = rawOrderOutService.findOrderInfo24(rawOrderOutDtoNew);
		
		if(orderOutDtos1 != null && !orderOutDtos1.isEmpty()) {
			for (RawOrderOutDto orderOutDto : orderOutDtos1) {
				BigDecimal realAmount = orderOutDto.getRealAmount() == null ? BigDecimal.ZERO
						: orderOutDto.getRealAmount();
				BigDecimal requireAmount = orderOutDto.getRequireAmount() == null ? BigDecimal.ZERO
						: orderOutDto.getRequireAmount();
				if (realAmount.compareTo(requireAmount) == -1) {
					resp.setCode(Constant.FAIL);
					resp.setMsg("该领料单号下还有未扫码完成的任务！");
					return resp;
				}
			}
		}

		RawRequisitionSn rawRequisitionSn = new RawRequisitionSn();
		rawRequisitionSn.setRequisitionNo(rawOrderOutDto.getRequisitionNo());
//      0未传mes;1已传mes
		rawRequisitionSn.setMesStatus("0");
		rawRequisitionSn.setActiveFlag("1");
		List<RawRequisitionSn> list = iMaterialRequisitionService.queryMesNormalList(rawRequisitionSn);

		if (list == null || list.isEmpty()) {
			// 3.确认完成，修改发货状态（出库主表：出库完成）
			rawOrderOutDto.setLastModifiedBy(rawOrderOutDto.getLoginName());
			rawOrderOutDto.setGmtModified(new Date());
			rawOrderOutService.updateTwo(rawOrderOutDto);
		} else {
			String url = mesProperties.getUrl() + "/imes-provider/productplan/follow/ordersplit/materialin";

			List<RawRequisitionMesDto> mesList = new ArrayList<RawRequisitionMesDto>();
			for (RawRequisitionSn tmp : list) {
				RawRequisitionMesDto mesOb = new RawRequisitionMesDto();
				mesOb.setMaterialId(tmp.getBarcode());
				mesOb.setMaterialCode(tmp.getModel());
				mesOb.setMaterialType(tmp.getModelType());
				mesOb.setQuantity(tmp.getAmount());
				mesOb.setMeasureUnit(tmp.getUnit());
				mesList.add(mesOb);
			}

			JSONObject ob = new JSONObject();
			ob.put("receiptNo", rawOrderOutDto.getRequisitionNo());
			ob.put("salesCode", list.get(0).getContractNo());
//          领料类型 1 普通料（钢管、pe管、管件） 2 辅料
			ob.put("type", "1");
			ob.put("materialList", mesList);
//    		调mes新增接口
			HandResp handResp = mesInterfaceService.publicWSResp(url, MediaType.APPLICATION_JSON_TYPE,
					ob.toJSONString());
			if (handResp.getCode() != null && handResp.getCode().equals("0")) {
				resp.setCode(handResp.getCode());
				resp.setMsg(handResp.getMsg());
				return resp;
			} else {
//    			更新是否上传mes状态
				iMaterialRequisitionService.updateMesStatus(list, rawOrderOutDto.getLoginName());
				// 3.确认完成，修改发货状态（出库主表：出库完成）
				rawOrderOutDto.setLastModifiedBy(rawOrderOutDto.getLoginName());
				rawOrderOutDto.setGmtModified(new Date());
				rawOrderOutService.updateTwo(rawOrderOutDto);
			}
		}

		resp.setCode(Constant.SUCCESS);
		resp.setMsg("确认成功！");
		return resp;
	}

	/**
	 * 查询领料单领料进度信息
	 *
	 * @return
	 */
	@PostMapping("info/jindu")
	public HandResp infoJindu(@RequestBody RawOrderOutDto rawOrderOutDto) {

		HandResp result = new HandResp();
		RawRequisition rawRequisition = new RawRequisition();
		rawRequisition.setActiveFlag("1");
		rawRequisition.setRequisitionNo(rawOrderOutDto.getRequisitionNo());
		rawRequisition.setRequisitionType02("02");
		List<RawRequisition> list = rawOrderOutSnService.queryByAnyList(rawRequisition);
		if (list == null || list.isEmpty()) {
			result.setCode(Constant.FAIL);
			result.setMsg("该领料单号不存在或单据为返修单!");
			return result;
		}else {
			for(RawRequisition t : list) {
				if(t.getRequisitionType().equals("0")) {
					t.setRequisitionType("普通-匹配");
				}else if(t.getRequisitionType().equals("2")) {
					t.setRequisitionType("普通-独发");
				}else if(t.getRequisitionType().equals("4")) {
					t.setRequisitionType("补料");
				}
			}
		}
		result.setCode(Constant.SUCCESS);
		result.setList(list);
		return result;
	}

	/**
	 * 查询领料单匹配关系
	 *
	 * @return
	 */
	@PostMapping("info")
	public HandResp info(@RequestBody RawOrderOutDto rawOrderOutDto) {
		HandResp result = new HandResp();
		RawRequisitionSn rawRequisitionSn = new RawRequisitionSn();
		rawRequisitionSn.setRequisitionNo(rawOrderOutDto.getRequisitionNo());
		rawRequisitionSn.setModelType(Constant.MODEL_PE);
		List<RawRequisitionSn> list = rawOrderOutSnService.queryScanInfo(rawRequisitionSn);
		result.setCode(Constant.SUCCESS);
		result.setList(list);
		return result;
	}

}